package com.atguigu.gmall.order.interceptor;

import com.atguigu.gmall.order.bean.UserInfo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    private static ThreadLocal<UserInfo> THREAD_LOCAL = new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取登录用户的userId透传给后续的服务: 网关的过滤器 获取了登录成功用户的userId设置到了请求头中
        String userId = request.getHeader("userId");
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(Long.parseLong(userId));
        THREAD_LOCAL.set(userInfo);
        return true;
    }
    public static Long getUserId(){
        return THREAD_LOCAL.get().getUserId();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        THREAD_LOCAL.remove();
    }
}
